package com.house.web.controller.system;

import com.house.common.config.HouseConfig;
import com.house.common.constant.UserConstants;
import com.house.common.core.controller.BaseController;
import com.house.common.core.domain.AjaxResult;
import com.house.common.core.domain.entity.User;
import com.house.common.core.domain.model.LoginUser;
import com.house.common.utils.StringUtils;
import com.house.common.utils.file.FileUploadUtils;
import com.house.framework.web.service.TokenService;
import com.house.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/entity/user/profile")
public class ProfileController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private TokenService tokenService;


    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        LoginUser loginUser = getLoginUser();
        User user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(HouseConfig.getAvatarPath(), file);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                AjaxResult ajax = AjaxResult.success();
                System.out.println("imgUrl: " + avatar);
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 个人证件上传
     */
    @PostMapping("/documents")
    public AjaxResult documents(@RequestParam("documentsfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = getLoginUser();
            String documents = FileUploadUtils.upload(HouseConfig.getDocumentsPath(), file);
            if (userService.updateUserDocuments(loginUser.getUsername(), documents)) {
                AjaxResult ajax = AjaxResult.success();
                System.out.println("imgUrl: " + documents);
                ajax.put("imgUrl", documents);
                // 更新缓存用户个人证件
                loginUser.getUser().setDocuments(documents);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult updateProfile(@RequestBody User user) {
        LoginUser loginUser = getLoginUser();

        //获取当前用户对象
        User sysUser = loginUser.getUser();

        user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhone()) &&
                !user.getPhone().equals(sysUser.getPhone()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !user.getEmail().equals(sysUser.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        if (userService.updateUserProfile(user) > 0) {
            // 更新缓存用户信息
            sysUser.setNickName(user.getNickName());
            sysUser.setPhone(user.getPhone());
            sysUser.setEmail(user.getEmail());
            sysUser.setGender(user.getGender());
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }
}
